package com.nidu.demo.security.util;

import com.nidu.demo.common.constants.RequestHeaderConstants;
import com.nidu.demo.security.core.LoginUser;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

/**
 * 安全服务组件
 *
 * @author auto
 */
@Component
public class SecurityUtils {

    public SecurityUtils() {}

    /**
     * 从请求中，获得认证 Token
     *
     * @param request 请求
     * @param token 认证 Token 对应的 Header 名字
     * @return 认证 Token
     */
    public static String getTokenFromRequest(HttpServletRequest request, String token) {
        String authorization = request.getHeader(token);
        if (!StringUtils.hasText(authorization)) {
            return null;
        }
        int index = authorization.indexOf(RequestHeaderConstants.AUTHORIZATION_BEARER + " ");
        if (index == -1) { // 未找到
            return null;
        }
        return authorization.substring(index + 7).trim();
    }

    /**
     * 获得当前认证信息
     *
     * @return 认证信息
     */
    public static Authentication getAuthentication() {
        SecurityContext context = SecurityContextHolder.getContext();
        if (context == null) {
            return null;
        }
        return context.getAuthentication();
    }

    /**
     * 获取当前用户
     *
     * @return 当前用户
     */
    @Nullable
    public static LoginUser getLoginUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return authentication.getPrincipal() instanceof LoginUser ? (LoginUser) authentication.getPrincipal() : null;
    }

    /**
     * 获得当前用户的编号，从上下文中
     *
     * @return 用户编号
     */
    @Nullable
    public static Long getLoginUserId() {
        LoginUser loginUser = getLoginUser();
        return loginUser != null ? loginUser.getId() : null;
    }

    /**
     * 获得当前用户的编号，从上下文中
     *
     * @return 用户编号
     */
    @Nullable
    public static Integer getLoginUserType() {
        LoginUser loginUser = getLoginUser();
        return loginUser != null ? loginUser.getUserType() : null;
    }

    /**
     * 设置当前用户
     *
     * @param loginUser 登录用户
     * @param request 请求
     */
    public static void setLoginUser(LoginUser loginUser, HttpServletRequest request) {
        // 创建 Authentication，并设置到上下文
        // 创建 UsernamePasswordAuthenticationToken 对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                loginUser, null, Collections.emptyList());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }

    /**
     * 判断当前用户是否已认证
     */
    public static boolean isAuthenticated() {
        Authentication authentication = getAuthentication();
        return authentication != null && authentication.isAuthenticated();
    }

    /**
     * 从请求中，获得认证
     * @param request
     * @param token
     * @return
     */
    public static String getClientFromRequest(HttpServletRequest request, String token) {
        String authorization = request.getHeader(token);
        if (!StringUtils.hasText(authorization)) {
            return null;
        }
        int index = authorization.indexOf(RequestHeaderConstants.AUTHORIZATION_BEARER + " ");
        if (index == -1) { // 未找到
            return null;
        }
        return authorization.substring(index + 7).trim();
    }
}
